<!--
 * @Descripttion:
 * @version:
 * @Editor: E-CHOOSEUS R&D
 * @LastEditors: E-CHOOSEUS R&D
-->
<template>
  <div class="index">
    <div class="act-bar">
      <el-date-picker
        v-model="datetimeRange"
        class="left"
        :clearable="false"
        type="datetimerange"
        format="yyyy-MM-dd HH:mm"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :pickerOptions="pickerOptions"
      >
      </el-date-picker>
      <img
        class="refresh left ml-10"
        src="@/assets/images/refresh.png"
        @click="reset"
      />
      <!-- <el-button type="primary" @click="add"> 新 增 </el-button> -->
      <el-button
        v-has="'nursingDoc:edit'"
        type="primary"
        class="my-btn"
        @click="beforeSave"
      >
        保 存
      </el-button>
      <el-button
        v-has="'nursingDoc:export'"
        class="my-btn"
        :loading="isExporting"
        @click="handleOutput"
      >
        导 出
      </el-button>
      <el-button v-has="'nursingDoc:export'" class="my-btn" @click="print"
        >打 印</el-button
      >
      <button
        v-show="false"
        ref="printBtn"
        v-has="'nursingDoc:export'"
        v-print="printConf"
        class="my-btn"
      >
        打 印
      </button>
    </div>
    <div class="multi-container">
      <div id="printDom" v-loading="loading" class="printMain">
        <div
          v-for="(item, index) in pages"
          :key="index"
          :ref="e => (printDoms[index] = e)"
          class="doc-container"
          :class="'doc-container' + index"
        >
          <i
            v-show="index > 0 && !isPrinting && !isExporting"
            class="remove-icon el-icon-close"
            @click="remove(index, item)"
          ></i>
          <DocHeader :title="getTitle()" fromDoc="mechanicalVentilation" />
          <mainPage ref="formRef" :data="item" :page-index="index" />
        </div>
      </div>
    </div>
    <div class="pagination">
      <div
        v-for="(item, index) in pages"
        :key="index"
        class="item"
        @click="handlePageIntoView(index)"
      >
        {{ index + 1 }}
      </div>
    </div>
  </div>
</template>

<script>
import { endOfDay, format, startOfDay } from 'date-fns'
import { cloneDeep } from 'lodash-unified'
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  toRefs,
  watch
} from 'vue'
import { useRouter } from 'vue-router/composables'

import { Doc } from '@/api/doc'
import { estimate } from '@/api/nursing/operate'
import {
  getElementFnFromInstance,
  getStoreFromInstance
} from '@/utils/instance'

import { useDocExport } from '../../hooks'
import DocHeader from '../DocHeader.vue'
import { baseData } from './baseData'
import mainPage from './mainPage.vue'

export default defineComponent({
  name: 'BloodSupplyObserve',
  components: { mainPage, DocHeader },
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  setup(props) {
    const state = reactive({
      printConf: {
        id: 'printDom',
        popTitle: '打印', // 打印配置页上方标题
        extraHead: '', //最上方的头部文字，附加在head标签上的额外标签,使用逗号分隔
        preview: '', // 是否启动预览模式，默认是false（开启预览模式，可以先预览后打印）
        previewTitle: '', // 打印预览的标题（开启预览模式后出现）,
        previewPrintBtnLabel: '', // 打印预览的标题的下方按钮文本，点击可进入打印（开启预览模式后出现）
        zIndex: '', // 预览的窗口的z-index，默认是 20002（此值要高一些，这涉及到预览模式是否显示在最上面）
        previewBeforeOpenCallback() {}, //预览窗口打开之前的callback（开启预览模式调用）
        previewOpenCallback() {}, // 预览窗口打开之后的callback（开启预览模式调用）
        beforeOpenCallback() {}, // 开启打印前的回调事件
        openCallback() {}, // 调用打印之后的回调事件
        closeCallback(vue) {
          vue.isPrinting = false
        }, //关闭打印的回调事件（无法确定点击的是确认还是取消）
        url: '',
        standard: '',
        extraCss: ''
      },
      loading: false, //加载中
      pages: [], //表格数据
      isPrinting: false,
      isExporting: false,
      form: {},
      recordData: [],
      printBtn: {},
      printDoms: [],
      formRef: [],
      pageNum: 16,
      datetimeRange: [],
      dataDoc: {},
      dict: {
        hx_type: [],
        config_mode: []
      },
      pickerOptions: {}
    })

    const { handleDocExportMulti } = useDocExport()
    const store = getStoreFromInstance()
    const { $confirm, $message } = getElementFnFromInstance()
    const router = useRouter()

    const patCur = computed(() => store.getters.patCur)

    const isHistory = computed(() => store.getters.isHistory)

    function getDict() {
      estimate.getDict({ obsvCode: 'hx_type' }).then(({ data }) => {
        if (data) {
          state.dict.hx_type = data.map(res => {
            return {
              code: res.obsvCode,
              name: res.obsvName
            }
          })
        }
      })

      estimate.getDict({ obsvCode: 'config_mode' }).then(({ data }) => {
        if (data) {
          state.dict.config_mode = data.map(res => {
            return {
              code: res.obsvCode,
              name: res.obsvName
            }
          })
        }
      })
    }

    getDict()

    function filterDict(tag, arr) {
      if (tag) {
        const obj = arr.find(res => res.code === tag)
        return obj?.name || tag
      }
      return ''
    }

    async function initData() {
      state.loading = true
      if (!patCur.value) {
        return
      }
      const params = {
        hospitalNumber: patCur.value.hospitalNumber,
        startItemTime: +new Date(state.datetimeRange[0]),
        endItemTime: +new Date(state.datetimeRange[1]) || '',
        type: 52
      }
      const { data } = await Doc.getMVList(params)
      state.dataDoc = data.doc
      let tableData = data.docItems
      // docItems
      state.pages.length = 0
      const len = tableData.length
      if (len == 0) {
        state.recordData = []
        const arr = []
        for (let x = 0; x < state.pageNum; x++) {
          arr.push(baseData())
        }
        state.pages.push(arr)
      } else {
        const recordData = tableData.map(item => {
          if (item.jsonText && item.jsonText !== '{}') {
            try {
              item.jsonText = JSON.parse(item.jsonText)
            } catch (error) {
              item.jsonText = {}
            }
            for (const i in baseData()) {
              if (!item.jsonText[i]) {
                item.jsonText[i] = baseData()[i]
              }
            }

            const hx_type = filterDict(
              item.jsonText.hx_type,
              state.dict.hx_type
            )

            const config_mode = filterDict(
              item.jsonText.config_mode,
              state.dict.config_mode
            )

            const obj = {
              ...item,
              ...item.jsonText,
              hx_type,
              config_mode
            }

            // if (!obj.vtDiy) {
            //   if (obj.vti || obj.vte) {
            //     obj.vtDiy = `${obj.vti}|${obj.vte}`
            //   }
            // }
            return { ...obj }
          }
          return ''
        })

        tableData = cloneDeep(recordData)

        for (let i = 0; i < tableData.length; i = i + state.pageNum) {
          const arr = tableData.slice(i, state.pageNum + i)
          if (arr.length < state.pageNum) {
            const remainNum = state.pageNum - arr.length
            for (let x = 0; x < remainNum; x++) {
              arr.push(baseData())
            }
          }
          state.pages.push(arr)
        }
      }
      state.loading = false
    }

    function add() {
      const arr = []

      for (let x = 0; x < state.pageNum; x++) {
        arr.push(baseData())
      }

      state.pages.push(arr)

      nextTick(() => {
        const wrapper = document.querySelector('.multi-container')
        const items = document.querySelectorAll('.doc-container')
        const lastItem = items[items.length - 1]
        wrapper.scroll({
          top: lastItem.offsetTop - 82,
          behavior: 'smooth'
        })
      })
    }

    async function beforeSave() {
      const arr = []
      for (const formRef of state.formRef) {
        let tableData = cloneDeep(formRef.getParams())
        tableData = tableData.map(res => {
          delete res.nanoid
          return {
            createTime: res.mappedTime
              ? format(res.mappedTime, 'yyyy-MM-dd HH:mm:ss')
              : '',
            id: res.id ? res.id : null,
            icuDocRecordId: res.icuDocRecordId ? res.icuDocRecordId : null,
            jsonText: JSON.stringify(res)
          }
        })
        arr.push(...tableData)
      }
      save(arr)
    }

    function save(list) {
      const { createTime, updateTime, ...doc } = state.dataDoc
      const para = {
        doc,
        docItems: list
      }
      // 修改
      Doc.editMVList(para).then(res => {
        if (res.code === 0) {
          $message.success(`保存成功`)
        }
      })
    }

    function returnDom() {
      return state.printDoms
    }

    function handleOutput() {
      // this.loading = true;
      state.isExporting = true
      setTimeout(() => {
        handleDocExportMulti(
          state.printDoms,
          '',
          props.data.title + '.pdf',
          () => {
            state.isExporting = false
          }
        )
      }, 500)
    }

    function print() {
      state.isPrinting = true
      nextTick(() => {
        state.printBtn.click()
      })
    }

    function remove(index, item) {
      const isAdd = item.filter(res => res.id).length == 0
      $confirm('是否删除此页？')
        .then(() => {
          // 删除非新增项时执行保存操作
          if (!isAdd) {
            nextTick(() => {
              const ids = item.map(res => res.id)
              Doc.delMVList(ids).then(res => {
                if (res.code === 0) {
                  state.pages.splice(index, 1)
                }
              })
            })
          } else {
            state.pages.splice(index, 1)
          }
        })
        .catch(() => {})
    }

    function getTitle() {
      return props.data.title
    }

    function handlePageIntoView(index) {
      document.querySelector('.doc-container' + index)?.scrollIntoView()
    }

    function reset() {
      let startTime = +new Date(),
        endTime = +new Date()
      if (patCur.value.startRkTime) {
        startTime = new Date(patCur.value.startRkTime)
      }
      if (patCur.value.endCkTime) {
        endTime = new Date(patCur.value.endCkTime)
      }
      state.datetimeRange = [startTime, endTime]
    }

    watch(
      patCur,
      val => {
        if (val) {
          reset()
        }
        initData()
      },
      { immediate: true }
    )

    watch(
      () => state.datetimeRange,
      () => {
        initData()
      }
    )

    return {
      ...toRefs(state),
      beforeSave,
      initData,
      reset,
      add,
      returnDom,
      handleOutput,
      print,
      remove,
      getTitle,
      handlePageIntoView
    }
  }
})
</script>

<style lang="scss" scoped>
.index {
  height: calc(100% - 15px);
}

.act-bar {
  min-height: 52px;
  margin-bottom: 10px;
  padding: 9px 10px;
  text-align: right;
  border-bottom: 1px solid #f2f4f5;
}

.multi-container {
  height: calc(100% - 102px);
  padding-bottom: 20px;
  overflow-y: auto;
}

.printMain {
  width: 1188px;
  margin: 0 auto;
}

.doc-container {
  position: relative;
  margin: 0 auto;
  width: 1188px;
  height: 840px;
  background-color: #fff;
  border: 1px solid #f0f0f0;
  padding: 20px;

  .remove-icon {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 22px;
    font-weight: bold;
    color: red;
    cursor: pointer;
  }
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;

  .item {
    width: 32px;
    height: 32px;
    border-radius: 2px;
    margin: 0 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    background-color: #f4f4f5;
    color: #606266;
    cursor: pointer;
  }
}

.pageNum {
  margin-top: 18px;
  margin-bottom: 15px;
}

.refresh {
  width: 32px;
  padding: 8px;
  background: #155ef3;
  border-radius: 4px;
  cursor: pointer;
  vertical-align: top;
}
</style>
